<?php

namespace App\Admin\Controllers;

use App\Models\Club;
use App\Models\School;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;

class SchoolController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = 'School';

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new School());

        $grid->column('id', __('Id'));
        $grid->column('school_name', __('学校名称'));
        $grid->column('created_at', __('创建时间'));
        $grid->column('updated_at', __('更新时间'));

        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(School::findOrFail($id));

        $show->field('id', __('Id'));
        $show->field('school_name', __('学校名称'));
        $show->school_class_and_grade('年级/班级',function ($schoolClassAndGrade){
            $schoolClassAndGrade->resource('/admin/school-class-and-grades');
            $schoolClassAndGrade->disableCreateButton();
            $schoolClassAndGrade->disableExport();
            $schoolClassAndGrade->disableColumnSelector();
            $schoolClassAndGrade->column('id','ID');
            $schoolClassAndGrade->column('grade','年级');
            $schoolClassAndGrade->column('class_name','班级');
            $schoolClassAndGrade->column('club.club_name','社团班级');
            $schoolClassAndGrade->column('status','状态')->display(function ($status) {
                $text = $status === 1?'启用':'禁用';
                return "<span>$text</span>";
            });
            $schoolClassAndGrade->model()->orderBy('status');
            $schoolClassAndGrade->actions(function ($actions) {
                // 去掉查看
                $actions->disableView();
            });
        });
        $show->field('created_at', __('创建时间'));
        $show->field('updated_at', __('更新时间'));

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new School());

        $form->text('school_name', __('学校名称'));

        $form->hasMany('school_class_and_grade','班级/年级', function (Form\NestedForm $form) {
            $form->text('grade','年级');
            $form->text('class_name','班级名称');
            $form->radio('status','状态')->options([1=>'启用',2=>'禁用']);
            $form->select('club_id','社团班级')->options(Club::all()->pluck('club_name','id'));
        });

        return $form;
    }
}
